package com.zhuang.sms.netty;

import com.zhuang.sms.netty.decoder.CustomProtobufDecoder;
import com.zhuang.sms.netty.handler.TextWebSocketFrameHandler;
import com.zhuang.sms.netty.handler.WebSocketProtobufHandler;
import com.zhuang.sms.proto.ChatMessageOuterClass;
import com.zhuang.sms.proto.ChatMessageOuterClass.ChatMessage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class NettyWebSocketServer {

    private static final Logger LOGGER = Logger.getLogger(NettyWebSocketServer.class.getName());

    @Value("${netty.port: 7777}")
    private int port;

    @Autowired
    private TextWebSocketFrameHandler textWebSocketFrameHandler;

    public NettyWebSocketServer() {
    }

    public NettyWebSocketServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(
                             new HttpResponseEncoder(),
                             new HttpRequestDecoder(),
                             new HttpObjectAggregator(65536),
                             new WebSocketServerProtocolHandler("/zq"));//textWebSocketFrameHandler//

                     // Protobuf解码器与编码器
                     ch.pipeline().addLast(new CustomProtobufDecoder(ChatMessage.getDefaultInstance()));
//                     ch.pipeline().addLast(new ProtobufDecoder(ChatMessageOuterClass.ChatMessage.getDefaultInstance()));
                     ch.pipeline().addLast(new ProtobufEncoder());

                     // 添加自定义的WebSocket业务逻辑处理器
//                     ch.pipeline().addLast(textWebSocketFrameHandler);
                     ch.pipeline().addLast(new WebSocketProtobufHandler());
                 }
             });

            LOGGER.log(Level.INFO, "netty服务器启动成功！端口：{0}",String.valueOf(port));
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

//    public static void main(String[] args) throws Exception {
//        new NettyWebSocketServer(8080).start();
//    }


}